import SparkMD5 from 'spark-md5';

const DEFAULT_SIZE = 20 * 1024 * 1024;
const md5 = (file, chunkSize = DEFAULT_SIZE) => {
  return new Promise((resolve, reject) => {
    const blobSlice =
      File.prototype.slice ||
      File.prototype.mozSlice ||
      File.prototype.webkitSlice;
    const chunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;
    const spark = new SparkMD5.ArrayBuffer(); // 追加数组缓冲区。
    const fileReader = new FileReader(); // 读取文件
    fileReader.addEventListener('load', (e) => {
      spark.append(e.target.result);
      currentChunk++;
      if (currentChunk < chunks) {
        loadNext();
      } else {
        const md5 = spark.end(); // 完成md5的计算，返回十六进制结果。
        // console.log(
        //   '文件md5计算结束，总耗时：',
        //   (Date.now() - startMs) / 1000,
        //   's',
        // );
        resolve(md5);
      }
    });
    // eslint-disable-next-line unicorn/prefer-add-event-listener
    fileReader.onerror = function (e) {
      reject(e);
    };

    function loadNext() {
      // console.log('当前part number：', currentChunk, '总块数：', chunks);
      const start = currentChunk * chunkSize;
      let end = start + chunkSize;
      end > file.size && (end = file.size);
      // eslint-disable-next-line unicorn/prefer-blob-reading-methods
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }
    loadNext();
  });
};

export default md5;
